package io.github.talelin.latticy.controller.v1;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import io.github.talelin.latticy.service.StudentService;
import io.github.talelin.latticy.vo.CreatedVO;
import io.github.talelin.latticy.vo.DeletedVO;
import io.github.talelin.latticy.vo.UpdatedVO;
import io.github.talelin.autoconfigure.exception.NotFoundException;
import io.github.talelin.core.annotation.GroupRequired;
import io.github.talelin.core.annotation.PermissionMeta;
import javax.validation.constraints.Positive;
import java.util.List;
import io.github.talelin.latticy.dto.student.CreateOrUpdateStudentDTO;
import io.github.talelin.latticy.model.StudentDO;

/**
*
* @author vvboy
*/
@RestController
@RequestMapping("/v1/student")
@Validated
public class StudentController {

    @Autowired
    private StudentService studentService;

    @GetMapping("/{id}")
    public StudentDO getStudent(@PathVariable(value = "id") @Positive(message = "{id.positive}") Integer id) {
        StudentDO student = studentService.getById(id);
        if (student == null) {
            throw new NotFoundException("找不到", 10022);
        }
        return student;
    }

    @GetMapping("")
    public List<StudentDO> getStudents() {
        return studentService.findAll();
    }


    @PostMapping("")
    public CreatedVO createStudent(@RequestBody @Validated CreateOrUpdateStudentDTO validator) {
    studentService.createStudent(validator);
        return new CreatedVO(12);
    }


    @PutMapping("/{id}")
    public UpdatedVO updateStudent(@PathVariable("id") @Positive(message = "{id.positive}") Integer id, @RequestBody @Validated CreateOrUpdateStudentDTO validator) {
    StudentDO student = studentService.getById(id);
        if (student == null) {
        throw new NotFoundException(10022);
        }
    studentService.updateStudent(student, validator);
        return new UpdatedVO(13);
    }


    @DeleteMapping("/{id}")
    @GroupRequired
    @PermissionMeta(value = "删除学生表", module = "学生表")
    public DeletedVO deleteStudent(@PathVariable("id") @Positive(message = "{id.positive}") Integer id) {
    StudentDO student = studentService.getById(id);
    if (student == null) {
    throw new NotFoundException(10022);
    }
    studentService.deleteById(student.getId());
    return new DeletedVO(14);
    }

}